<template>
    <div>
        <!-- 搜索框 -->
        <el-row :gutter="30">
            <el-col :span="5">
                <el-input placeholder="请输入用户名" v-model="searchItem.a" size="small">
                    <i slot="prefix" class="el-input__icon el-icon-search"></i>
                </el-input>
            </el-col>
            <el-col :span="5">
                <el-input placeholder="请输入手机号" v-model="searchItem.b" size="small">
                    <i slot="prefix" class="el-input__icon el-icon-search"></i>
                </el-input>
            </el-col>
            <el-col :span="5">
                <el-input placeholder="请输入姓名" v-model="searchItem.c" size="small">
                    <i slot="prefix" class="el-input__icon el-icon-search"></i>
                </el-input>
            </el-col>
            <!-- 搜索按钮 -->
            <el-col :span="2">
                <el-button type="primary" icon="el-icon-search" size="small" @click="searchMessage()">搜索</el-button>
            </el-col>
            <!-- 重置搜索条件按钮 -->
            <el-col :span="2">
                <el-button type="warning" icon="el-icon-refresh-right" size="small"
                    @click="resetSearch()">重置</el-button>
            </el-col>
        </el-row>
        <!-- 按钮 -->
        <el-col :span="24">
            <el-button type="primary" icon="el-icon-plus" size="small" @click="dialogVisible2 = true">新增</el-button>
            <el-button type="success" icon="el-icon-edit" size="small" @click="dialogVisible = true"
                :disabled="isdisabled">修改</el-button>
            <el-button type="danger" icon="el-icon-delete" size="small" @click="deleteUser(user.userId)"
                :disabled="isdisabled">删除</el-button>
            <el-button type="primary" icon="el-icon-refresh-right" size="small" @click="resetPassword()"
                :disabled="isdisabled">重置密码</el-button>
            <el-button @click="setCurrent()" size="small" type="warning">取消选择</el-button>

        </el-col>
        <!-- 用户信息表格 -->
        <el-table ref="singleTable" :data="users.slice((currentPage-1)*pageSize,currentPage*pageSize)"
            style="width: 100%" highlight-current-row @row-click="dataChange" height="370px">
            <el-table-column prop="userId" label="id" sortable width="120px">
            </el-table-column>
            <el-table-column prop="username" label="用户名" sortable width="120px">
            </el-table-column>
            <el-table-column prop="realName" label="姓名" sortable width="120px">
            </el-table-column>
            <el-table-column prop="sex" label="性别" sortable width="80px">
            </el-table-column>
            <el-table-column prop="tel" label="手机号" sortable width="120px">
            </el-table-column>
            <el-table-column prop="address" label="住址" sortable width="120px" show-overflow-tooltip="true">
            </el-table-column>
            <el-table-column prop="userType" label="用户类型" sortable width="120px">
                <template slot-scope="scope">
                    <span v-if="scope.row.userType == 0" style="color: red;">禁用</span>
                    <span v-else>{{scope.row.userType == 1? "管理员":"用户"}}</span>
                </template>
            </el-table-column>
            <el-table-column prop="userType" label="用户状态" sortable width="120px">
                <template slot-scope="scope">
                    <el-button @click="setUserType(scope.row)" size="mini" type="success"
                        v-if="scope.row.userType == 0">启用</el-button>
                    <el-button @click="setUserType(scope.row)" size="mini" type="danger"
                        v-if="scope.row.userType == 2">禁用</el-button>
                    <el-button size="mini" type="danger" disabled v-if="scope.row.userType == 1">禁用</el-button>
                </template>
            </el-table-column>
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button size="mini" type="danger" @click="deleteUser(scope.row.userId)">删除</el-button>
                </template>
            </el-table-column>
            <el-table-column prop="updateTime" label="修改时间" sortable width="200px">
            </el-table-column>
        </el-table>
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
            :page-sizes="[6,20,50,100]" :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper"
            :total="users.length">
        </el-pagination>
        <!-- 修改信息弹出表单 -->
        <el-dialog title="信息修改" :visible.sync="dialogVisible" width="35%">
            <el-form ref="user" :model="user" label-width="80px">
                <el-form-item label="用户名">
                    <el-input readonly v-model="user.username"></el-input>
                </el-form-item>
                <el-form-item label="姓名">
                    <el-input v-model="user.realName"></el-input>
                </el-form-item>
                <el-form-item label="用户类型">
                    <template>
                        <el-radio v-model="user.userType" :label="1">管理员</el-radio>
                        <el-radio v-model="user.userType" :label="2">用户</el-radio>
                    </template>
                </el-form-item>
                <el-form-item label="性别">
                    <template>
                        <el-radio v-model="user.sex" label="男">男</el-radio>
                        <el-radio v-model="user.sex" label="女">女</el-radio>
                    </template>
                </el-form-item>
                <el-form-item label="手机号">
                    <el-input v-model="user.tel"></el-input>
                </el-form-item>
                <el-form-item label="住址">
                    <el-input v-model="user.address"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="updateUser(user)">确 定</el-button>
            </span>
        </el-dialog>
        <!-- 新增信息弹出表单 -->
        <el-dialog title="添加用户" :visible.sync="dialogVisible2" width="35%">
            <el-form ref="addUser" :model="newUser" label-width="80px">
                <el-form-item label="用户名">
                    <el-input v-model="newUser.username"></el-input>
                </el-form-item>
                <el-form-item label="密码">
                    <el-input v-model="newUser.password"></el-input>
                </el-form-item>
                <el-form-item label="姓名">
                    <el-input v-model="newUser.realName"></el-input>
                </el-form-item>
                <el-form-item label="用户类型">
                    <template>
                        <el-radio-group v-model="newUser.userType">
                            <el-radio :label="1">管理员</el-radio>
                            <el-radio :label="2">用户</el-radio>
                        </el-radio-group>
                        <!-- <el-radio v-model="newUser.userType" :value="1">管理员</el-radio>
                        <el-radio v-model="newUser.userType" :value="2">用户</el-radio> -->
                    </template>
                </el-form-item>
                <el-form-item label="性别">
                    <template>
                        <el-radio v-model="newUser.sex" label="男">男</el-radio>
                        <el-radio v-model="newUser.sex" label="女">女</el-radio>
                    </template>
                </el-form-item>
                <el-form-item label="手机号">
                    <el-input v-model="newUser.tel"></el-input>
                </el-form-item>
                <el-form-item label="住址">
                    <el-input v-model="newUser.address"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible2 = false">取 消</el-button>
                <el-button type="primary" @click="addUser(newUser)">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
    import { SelectAllUser, UpdateById, DeleteUserById, Register } from '@/api/index.js'
    import md5 from 'js-md5'
    export default {
        inject: ['reload'],
        data() {
            return {
                searchItem: {               // 查询条件
                    "a": "",
                    "b": "",
                    "c": "",
                },
                tempData: [],               // 查询结果
                messageCopy: [],           // 复制所有厂家信息（目的：减少接口调用）
                newUser: {},             // 新增用户信息
                users: [],               // 所有用户信息
                user: {},                // 修改用户信息
                dialogVisible: false,   // 修改表单显隐
                dialogVisible2: false,   // 新增表单显隐
                isdisabled: true,       // 按钮禁用
                currentPage: 1, // 当前页码
                total: 20, // 总条数
                pageSize: 6 // 每页的数据条数
            }
        },
        methods: {
            // 搜索
            searchMessage() {
                // 搜索信息为空，展示所有信息
                if (this.searchItem.a === '' && this.searchItem.b === '' && this.searchItem.c === '') {
                    this.users = this.messageCopy
                } else {
                    // 重置搜索条件
                    this.tempData = []
                    this.users = this.messageCopy
                    // 根据条件模糊查询
                    for (const item of this.users) {
                        if ((this.searchItem.a === '' || item.username.includes(this.searchItem.a)) &&
                            (this.searchItem.b === '' || item.tel.includes(this.searchItem.b)) &&
                            (this.searchItem.c === '' || item.realName.includes(this.searchItem.c))) {
                            // 符合条件，加入查询结果中
                            this.tempData.push(item)
                        }
                    }
                    // 展示查询结果
                    this.users = this.tempData
                }
            },
            // 重置查询条件
            resetSearch() {
                this.searchItem = {
                    "a": "",
                    "b": "",
                    "c": "",
                },
                    this.users = this.messageCopy
            },
            // 查询所有用户
            getUsers() {
                SelectAllUser().then((res) => {
                    this.users = res.data.data
                    this.messageCopy = res.data.data
                })
            },
            // 修改用户状态
            setUserType(user) {
                this.$confirm('此操作将修改此用户的登录权限, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    if (user.userType === 0) {
                        user.userType = 2
                    }
                    else if (user.userType === 2) {
                        user.userType = 0
                    }
                    UpdateById(user).then((res) => {
                        if (res.data.code === 200) {
                            this.$message({
                                type: 'success',
                                message: '修改成功!'
                            });
                        } else {
                            this.$message({
                                type: 'success',
                                message: res.data.msg
                            });
                        }
                    })

                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消修改'
                    });
                });

            },
            // 删除用户
            deleteUser(id) {
                this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    if (id === 10001) {
                        this.$message.error("超级管理员不允许删除！");
                    } else {
                        // 调用删除用户接口
                        DeleteUserById(id).then((res) => {
                            if (res.data.code === 200) {
                                this.$message({
                                    type: 'success',
                                    message: '删除成功!'
                                });
                                this.reload()
                            } else {
                                this.$message({
                                    type: 'success',
                                    message: res.data.msg
                                });
                            }
                        })
                    }
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });

            },
            // 修改用户信息
            updateUser(user) {
                // 关闭表单
                this.dialogVisible = false
                // 调用修改信息接口
                UpdateById(user).then((res => {
                    if (res.data.code === 200) {
                        this.$message.success(res.data.msg);
                        this.reload()
                    } else {
                        this.$message.error(res.data.msg);
                    }
                }))
            },
            // 新增用户
            addUser(newUser) {
                // 关闭表单
                this.dialogVisible2 = false
                newUser.password = md5(newUser.password + "lixiaoyu")
                // 调用注册接口
                Register(newUser).then((res) => {
                    if (res.data.code === 200) {
                        this.$message.success("添加成功")
                        this.reload()
                    } else {
                        this.$message.error(res.data.msg)
                    }
                })

            },
            // 重置密码
            resetPassword() {
                this.$confirm('此操作将重置此用户的密码, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.user.password = md5("123456" + "lixiaoyu")
                    // 调用修改信息接口
                    UpdateById(this.user).then((res) => {
                        if (res.data.code === 200) {
                            this.$message.success("密码已重置为123456");
                        } else {
                            this.$message.error(res.data.msg);
                        }
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消密码重置'
                    });
                });

            },
            // 选中一行数据
            dataChange(val) {
                this.isdisabled = false
                this.user = val;
            },
            //每页条数改变时触发 选择一页显示多少行
            handleSizeChange(val) {
                this.currentPage = 1;
                this.pageSize = val;
            },
            //当前页改变时触发 跳转其他页
            handleCurrentChange(val) {
                this.isdisabled = true
                this.currentPage = val;
            },
            // 取消选择
            setCurrent(row) {
                this.isdisabled = true
                this.$refs.singleTable.setCurrentRow(row);
            },
        },
        // 加载用户信息
        mounted() {
            this.getUsers()
        }

    }
</script>
<style scoped>
    .el-col-24 {
        margin-top: 13px;
        margin-bottom: 13px;
    }
</style>